package xyz.chaoslolomonica.recipes;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class LockExample {

	public static void main(String[] args) throws InterruptedException {
		CuratorFramework client = CuratorFrameworkFactory
				.newClient("127.0.0.1:2181", new ExponentialBackoffRetry(1000, 3));
		client.start();

		ExecutorService service = Executors.newFixedThreadPool(3);
		final DistributedLock lock = ZKDistributedLockImpl.create(client, "/example/lock", true);

		for (int i = 0; i < 3; ++i) {
			final int index = i;
			Callable<Void> task = new Callable<Void>() {

				@Override
				public Void call() throws Exception {
					for (int i = 0; i < 3; ++i) {
						System.out.println("Client #" + index + " waits on lock");
						lock.lock();
						System.out.println("Client #" + index + " passed lock and release lock");
						lock.unlock();
					}
					return null;
				}
			};
			service.submit(task);
		}

		Thread.sleep(10000);
		System.out.println("wait all task done.");

		service.shutdown();
		service.awaitTermination(10, TimeUnit.SECONDS);
		client.close();
	}
}
